﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace ProphetsWay.myMd5.Core
{
	public static class Md5Utilities
	{
		public static bool VerifyMd5(this FileInfo fileInfo, string validMd5)
		{
			return string.Equals(validMd5, fileInfo.GenerateMd5());
		}

		public static bool VerifyMd5(this Stream stream, string validMd5)
		{
			return string.Equals(validMd5, stream.GenerateMd5());
		}

		public static string GenerateMd5(string fileName)
		{
			var file = new FileInfo(fileName);
			return file.GenerateMd5();
		}

		public static string GenerateMd5(this FileInfo fileInfo)
		{
			return fileInfo.OpenRead().GenerateMd5();
		}

		public static string GenerateMd5(this Stream stream)
		{
			var crypto = new MD5CryptoServiceProvider();
			byte[] hash;

			try
			{
				hash = crypto.ComputeHash(stream);
			}
			finally
			{
				if (stream != null)
					stream.Close();
			}

			return BitConverter.ToString(hash).Replace("-", "").ToLower();
		}

	}
}
